package com.ruoyi.system.basicInformation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.basicInformation.model.TreeSelect;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.ruoyi.system.basicInformation.bo.TAreaAddBo;
import com.ruoyi.system.basicInformation.bo.TAreaQueryBo;
import com.ruoyi.system.basicInformation.bo.TAreaEditBo;
import com.ruoyi.system.basicInformation.domain.TArea;
import com.ruoyi.system.basicInformation.mapper.TAreaMapper;
import com.ruoyi.system.basicInformation.vo.TAreaVo;
import com.ruoyi.system.basicInformation.service.ITAreaService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 区域管理Service业务层处理
 *
 * @author ruoyi
 * @date 2022-08-08
 */
@Service
public class TAreaServiceImpl extends ServiceImpl<TAreaMapper, TArea> implements ITAreaService {

    @Override
    public TAreaVo queryById(Long id) {
        if (id == 0)
            id = SecurityUtils.getLoginUser().getUser().getAreaId() > 0 ? SecurityUtils.getLoginUser().getUser().getAreaId() : 0;
        TArea db = this.baseMapper.selectById(id);
        return BeanUtil.toBean(db, TAreaVo.class);
    }

    @Override
    public List<TAreaVo> queryList(TAreaQueryBo bo) {
        LambdaQueryWrapper<TArea> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getCode()), TArea::getCode, bo.getCode());
        lqw.like(StrUtil.isNotBlank(bo.getName()), TArea::getName, bo.getName());
        return entity2Vo(this.list(lqw));
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<TAreaVo> entity2Vo(Collection<TArea> collection) {
        List<TAreaVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, TAreaVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<TArea> page = (Page<TArea>) collection;
            Page<TAreaVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(TAreaAddBo bo) {
        TArea add = BeanUtil.toBean(bo, TArea.class);
        validEntityBeforeSave(add);
        return this.save(add);
    }

    @Override
    public Boolean updateByEditBo(TAreaEditBo bo) {
        TArea update = BeanUtil.toBean(bo, TArea.class);
        validEntityBeforeSave(update);
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(TArea entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

    @Override
    @DataScope(deptAlias = "d")
    public List<TArea> selectDeptList(TArea dept) {
        return baseMapper.selectDeptList(dept);
    }

    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<TArea> depts) {
        List<TArea> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<TArea> buildDeptTree(List<TArea> depts) {
        List<TArea> returnList = new ArrayList<TArea>();
        List<Long> tempList = new ArrayList<Long>();
        for (TArea dept : depts) {
            tempList.add(dept.getId());
        }
        for (Iterator<TArea> iterator = depts.iterator(); iterator.hasNext(); ) {
            TArea dept = (TArea) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    private void recursionFn(List<TArea> list, TArea t) {
        // 得到子节点列表
        List<TArea> childList = getChildList(list, t);
        t.setChildren(childList);
        for (TArea tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<TArea> getChildList(List<TArea> list, TArea t) {
        List<TArea> tlist = new ArrayList<TArea>();
        Iterator<TArea> it = list.iterator();
        while (it.hasNext()) {
            TArea n = (TArea) it.next();
            if (Validator.isNotNull(n.getParentId()) && n.getParentId().equals(t.getId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<TArea> list, TArea t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
